//
//  MKViewController.m
//  ChooseLocation
//
//  Created by Apple on 14/11/25.
//  Copyright (c) 2014年 Apple. All rights reserved.
//

#import "MKViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "ChooseCityViewController.h"
#import "MKHandleCityData.h"

@interface MKViewController ()<CLLocationManagerDelegate>

@property (nonatomic, strong) UIActivityIndicatorView * activityView;
@property (nonatomic, strong) CLLocationManager * locationManager;
@property (nonatomic, strong) CLGeocoder * geocoder;

@end

@implementation MKViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.navigationItem.leftBarButtonItem) {
        NSString * showCityString = [[NSUserDefaults standardUserDefaults] objectForKey:@"showCity"];
        MKHandleCityData * hanleData = [[MKHandleCityData alloc] init];
        self.navigationItem.leftBarButtonItem.title = [hanleData cityFormatWithString:showCityString];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    if (!self.navigationItem.leftBarButtonItem) {
        [self startLocation];
    }
    
    self.navigationController.navigationBar.barTintColor = [UIColor cyanColor];
    self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityView.frame = CGRectMake(0, 0, 64.0, 64.0);
    self.activityView.hidesWhenStopped = YES;
    [self.view addSubview:self.activityView];
    self.activityView.center = self.view.center;
    // 指示框开始旋转，当定位成功后停止旋转
    if (self.activityView.superview) {
        [self.activityView startAnimating];
    }
    
}

- (void)startLocation
{
    // 开始定位
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 8.0) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [self startTrackingLocation];
    } else {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 1;
        [_locationManager startUpdatingLocation];
    }
    
}

// iOS 8.0 之后的定位
- (void)startTrackingLocation
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        [_locationManager requestWhenInUseAuthorization];
    } else if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
        [_locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    [_locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // 创建一个定位对象
    CLLocation * theLocation = [[CLLocation alloc] initWithLatitude:manager.location.coordinate.latitude longitude:manager.location.coordinate.longitude];
    _geocoder = [[CLGeocoder alloc] init];
    [_geocoder reverseGeocodeLocation:theLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count > 0) {
            CLPlacemark * placeMark = [placemarks objectAtIndex:0];
            NSString * city = placeMark.locality; // 城市
            NSString * admiCity = placeMark.administrativeArea; // 直辖市
            
            BOOL isCityNil = [city isEqual:@""] || city == nil;
            BOOL isAdmiCityNil = [admiCity isEqual:@""] || admiCity == nil;
            
            if (!(isCityNil && isAdmiCityNil)) {
                // 当城市或直辖市存在，停止定位
                [manager stopUpdatingLocation];
                // 隐藏 旋转
                if (self.activityView.superview) {
                    [self.activityView stopAnimating];
                }
                
                NSString * rcity;
                
                if (!isCityNil) {
                    rcity = city;
                } else if (!isAdmiCityNil) {
                    rcity = admiCity;
                }
                MKHandleCityData * handleCityData = [[MKHandleCityData alloc] init];
                NSString * cityString = [handleCityData cityFormatWithString:rcity];
                // 存储定位到的城市
                [[NSUserDefaults standardUserDefaults] setObject:cityString forKey:@"city"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                // 显示左边
                self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:cityString style:UIBarButtonItemStylePlain target:self action:@selector(handleChooseCity:)];
            }
        }
    }];
}


- (void)handleChooseCity:(UIBarButtonItem *)barButtonItem
{
    ChooseCityViewController * chooseVC = [[ChooseCityViewController alloc] init];
    // 用Block传值会出现闪
//    [chooseVC sendSelectCity:^(NSString *seletString) {
//        self.navigationItem.leftBarButtonItem.title = [self cityFormatWithString:seletString];
//    }];
    [self.navigationController pushViewController:chooseVC animated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
